class HomeController < ApplicationController
  before_filter :app_login, :except => [:index, :login, :login_complete]

  def index
  end

  @@consumer_key = 'dJ6avYWkBJBKvrxaBZ5axA'
  @@consumer_secret = 'KGEW9lqp2hh7wGYxd5a9KAJtoM8mm93Yzed3JXSDo'
  def login
    oauth = OAuth::Consumer.new(@@consumer_key, @@consumer_secret,
                                 { :site => "http://twitter.com" })

    url = "http://taskdown.com/login_complete"
    request_token = oauth.get_request_token(:oauth_callback => url)

    session[:request_token] = request_token.token
    session[:request_token_secret] = request_token.secret

    redirect_to request_token.authorize_url
  end

  def login_complete
    oauth = OAuth::Consumer.new(@@consumer_key, @@consumer_secret,
                                 { :site => "http://twitter.com" })
    request_token = OAuth::RequestToken.new(oauth, session[:request_token],
                                            session[:request_token_secret])

    if !params[:denied].nil?
      flash[:error] = 'You need to login with the twitter account that you signed up with.'
      redirect_to :action => index
    else
      access_token = request_token.get_access_token
      response = oauth.request(:get, '/account/verify_credentials.json',
                               access_token, { :scheme => :query_string })
      user_info = JSON.parse(response.body)
      user = User.find_by_twitter_user_id(user_info["id"])

      if !user.nil?
        session[:user] = user.id
        redirect_to_stored
      else
        flash[:error] =  'sign up is simple follow us on twitter.'
        redirect_to :action => index
      end
    end
  end

end
